package com.maoshi.shop.user.api.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.ScoreLogType;
import com.maoshi.shop.bean.event.UpdateUserScoreEvent;
import com.maoshi.shop.bean.model.SysConfig;
import com.maoshi.shop.bean.model.UserExtension;
import com.maoshi.shop.bean.param.ScoreConfigParam;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.service.SysConfigService;
import com.maoshi.shop.service.UserExtensionService;
import com.maoshi.shop.user.comment.dto.ScoreDataDto;
import com.maoshi.shop.user.comment.model.UserLevel;
import com.maoshi.shop.user.comment.model.UserScoreLog;
import com.maoshi.shop.user.comment.service.UserLevelService;
import com.maoshi.shop.user.comment.service.UserScoreLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
 * 积分中心接口
 *
 * @author LHD
 * @date 2019-3-18 10:27:46
 */
@RestController
@RequestMapping("/p/score")
@Api(tags = "积分中心接口")
@AllArgsConstructor
public class UserScoreController {

    private final UserScoreLogService scoreLogService;
    private final ApplicationContext applicationContext;
    private final SysConfigService sysConfigService;
    private final UserExtensionService userExtensionService;
    private final UserLevelService userLevelService;


    @GetMapping("/updateUserScore")
    @ApiOperation(value = "积分签到", notes = "积分签到")
    public ResponseEntity<String> updateUserScore() {
        String userId = SecurityUtils.getUser().getUserId();
        ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG, ScoreConfigParam.class);
        //签到，计算连续签到日期
        if(isSignIn(userId)){
            return ResponseEntity.ok("今天已经签到过了，请明天再试！");
        }
        //根据逗号分隔
        String[] signInScore = scoreParam.getSignInScoreString().split(StrUtil.COMMA);
        Integer count = getCount(userId);
        count++;
        int score = Integer.parseInt(signInScore[count - 1]);
        String remarks = "签到第" + count + "天获取的积分";
        applicationContext.publishEvent(new UpdateUserScoreEvent(ScoreLogType.SIGN_IN.value(),score,1,
                null, remarks,userId));
        return ResponseEntity.ok("领取积分成功");
    }

    /**
     * 获取数据库的签到记录记录
     * @param userId
     * @return
     */
    private Integer getCount(String userId) {
        Integer count = scoreLogService.getConsecutiveDays(userId);
        //如果没有记录就是第一天签到
        if(count == null){
            count = 0;
        }
        //如果是第七天之后都是第七天的奖励
        count = Math.min(6,count);
        return count;
    }

    @GetMapping("/scoreInfo")
    @ApiOperation(value = "查看积分中心信息", notes = "查看积分中心信息")
    public ResponseEntity<ScoreDataDto> scoreInfo() {
        ScoreDataDto scoreDataDto = new ScoreDataDto();
        String userId = SecurityUtils.getUser().getUserId();
        ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG, ScoreConfigParam.class);
        ArrayList<Integer> signInScores = new ArrayList<>();
        for(String s : scoreParam.getSignInScoreString().trim().split(StrUtil.COMMA)){
            Integer signInScore = Integer.valueOf(s);
            signInScores.add(signInScore);
        }
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, userId));
        if (userExtension == null) {
            return ResponseEntity.ok().build();
        }
        scoreDataDto.setIsRegister(1);
        scoreDataDto.setGrowth(userExtension.getGrowth());
        scoreDataDto.setScore(userExtension.getScore());
        scoreDataDto.setScoreList(signInScores);
        scoreDataDto.setRegisterScore(scoreParam.getRegisterScore());
        scoreDataDto.setShopScore(scoreParam.getShopGetScore());
        scoreDataDto.setIsSignIn(isSignIn(userId)? 1:0);
        scoreDataDto.setLevelType(userExtension.getLevelType());
        UserLevel userLevel = userLevelService.getOne(new LambdaQueryWrapper<UserLevel>()
                .eq(UserLevel::getLevel, userExtension.getLevel())
                .eq(UserLevel::getLevelType, userExtension.getLevelType())
        );
        scoreDataDto.setLevelName(userLevel.getLevelName());
        //计算签到天数
        Integer count = scoreLogService.getConsecutiveDays(userId);
        //如果没有记录就是第一天签到
        if(count == null){
            count = 1;
        }
        count = Math.min(7,count);
        scoreDataDto.setSignInCount(isSignIn(userId)?count:count+ 1);
        return ResponseEntity.ok(scoreDataDto);
    }

    /**
     * 是否已经签到
     * @param userId
     * @return
     */
    private boolean isSignIn(String userId){
        List<UserScoreLog> scoreList = scoreLogService.list(new LambdaQueryWrapper<UserScoreLog>().eq(UserScoreLog::getSource, ScoreLogType.SIGN_IN.value())
                                                        .ge(UserScoreLog::getCreateTime, DateUtil.beginOfDay(DateUtil.date()))
                                                        .le(UserScoreLog::getCreateTime, DateUtil.endOfDay(DateUtil.date()))
                                                        .eq(UserScoreLog::getUserId, userId));
        return CollectionUtils.isNotEmpty(scoreList);
    }

    /**
     * 分页查询积分明细
     * @param page 分页对象
     * @return 分页数据
     */
    @GetMapping("/page" )
    @ApiOperation(value = "查询积分明细", notes = "查询积分明细")
    public ResponseEntity<IPage<UserScoreLog>> getScoreLogPage(PageParam<UserScoreLog> page) {
        String userId = SecurityUtils.getUser().getUserId();
        return ResponseEntity.ok(scoreLogService.page(page,new LambdaQueryWrapper<UserScoreLog>()
                .eq(UserScoreLog::getUserId,userId).orderByDesc(UserScoreLog::getCreateTime)));
    }


    /**
     * 积分说明
     * @return 积分说明
     */
    @GetMapping("/getScoreExplain" )
    @ApiOperation(value = "积分说明", notes = "积分说明")
    public ResponseEntity<SysConfig> getScoreExplain() {
        SysConfig config = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getParamKey,Constant.SCORE_EXPLAIN));
        if(Objects.isNull(config)){
            return ResponseEntity.ok(new SysConfig());
        }
        return ResponseEntity.ok(config);
    }

}
